package stackoverflow.domain.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.UncategorizedDataAccessException;
import org.springframework.stereotype.Service;

import stackoverflow.domain.question.Answer;
import stackoverflow.domain.question.Question;
import stackoverflow.domain.question.QuestionRepository;
import stackoverflow.domain.question.Tag;
import stackoverflow.domain.question.specification.QuestionSpecification;
import stackoverflow.domain.question.specification.QuestionTagSpecification;
import stackoverflow.domain.service.QuestionService;
import stackoverflow.domain.user.User;

@Service("questionServiceImpl")
public class QuestionServiceImpl implements QuestionService {
	
	private QuestionRepository questionRepository;

	@Autowired
	public QuestionServiceImpl(@Qualifier("questionRepositoryImpl")
			QuestionRepository questionRepository) {
		this.questionRepository = questionRepository;
	}

	public List<Question> viewQuestionsThatHaveTag(Set<Tag> tags) {
		List<Question> questionsThatHaveTag = new ArrayList<Question>();
		List<Question> allQuestions = questionRepository.findAll();
		QuestionSpecification questionSpecification = new QuestionTagSpecification(
				tags);
		for (Question question : allQuestions) {
			if (questionSpecification.isSatisfiedBy(question))
				questionsThatHaveTag.add(question);
		}
		return questionsThatHaveTag;
	}

	public Answer postAnswer(User user, String postIdOfQuestion,
			String answerText) {
		Question question = questionRepository
				.findQuestionById(postIdOfQuestion);
		Answer answer = new Answer(user, answerText);
		question.postAnswer(answer);
		return answer;
	}

	public List<Question> viewQuestions() {
		try {
			return questionRepository.findAll();
		} catch (UncategorizedDataAccessException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public Question askQuestion(User user, String questionText, Set<Tag> tags)
	{
		Question.QuestionBuilder questionBuilder = 
			new Question.QuestionBuilder(user).postText("Some random text.").addTags(tags);
		Question question = questionBuilder.build();
		questionRepository.add(question);
		return question;
	}

}
